#coding:utf-8
import math
from datetime import datetime, timedelta
import time
import colander
import deform
from pyramid.response import Response
from pyramid.view import view_config
from pyramid.httpexceptions import HTTPNotFound,HTTPFound
from pyramid.security import remember,forget
from sqlalchemy.exc import DBAPIError
from sqlalchemy import func

from ..models.annocement import Annoncement
from ..models.order import Order
from ..models.cart import Cart
from ..models.category import Category
from ..models.comment import Comment
from ..models.item import Item
from ..models.user import User
from ..models.meta import DBSession

from js.jquery import jquery

@view_config(route_name='home', renderer='../templates/index.jinja2',layout='master')
def index_view(request):
    items=request.dbsession.query(Item).order_by('add_time desc').limit(3).all()
    annoncements=request.dbsession.query(Annoncement).all()
    categories=request.dbsession.query(Category).filter_by(parent=None).all()
    return {'items':items,'annoncements':annoncements,'title':u'首页','categories':categories}

@view_config(route_name='category',renderer='../templates/category.jinja2',layout='master')
def catgory_view(request):
    #get id
    try:
        id=int(request.matchdict['id'])
    except:
        return 'Invalid ID'

    try:
        page=int(request.params.get('p',1))
    except:
        page=1

    try:
        start_price=int(request.params.get('start_price',0))
        end_price = int(request.params.get('end_price', 10000000))
    except:
        start_price=0
        end_price=10000000

    #当前的年月,拼接后续的默认时间
    now_year_month=time.strftime('%Y-%m',time.localtime(time.time()))

    #当前id的分类信息
    category=request.dbsession.query(Category).filter(Category.id==id).first()

    if not category:
        return HTTPNotFound()
    #获取父类信息
    category_old=request.dbsession.query(Category).filter_by(id=category.parent_id).first()
    # 当前分类为父类
    if not category_old:
        cat_id_list=[]
        #循环获取所有子类的id
        for category_value in category.children:
            cat_id_list.append(category_value.id)
        #使用in_  来执行find_in_set (Mysql)
        # show_items = request.dbsession.query(Item).filter(func.find_in_set(Item.category_id)).limit((page - 1) * 6).offset(6).all()
        show_items=request.dbsession.query(Item).filter(Item.category_id.in_(cat_id_list)).limit(6).offset((page-1)*6).all()
    else:
        show_items=request.dbsession.query(Item).filter(Item.category_id == category.id,Item.price>start_price,Item.price<end_price).limit(6).offset((page-1)*6).all()


    #计算item表中，一共有多少数据，用向上取整，来计算一共多少页
    item_count=request.dbsession.query(Item).count()
    total_page=int(math.ceil(item_count/6.0))

    return {'category':category,'category_old':category_old,'items':show_items,'title':u'分类列表','total_page':total_page,'page_num':page,'category_id':id}

@view_config(route_name='item',renderer='../templates/item.jinja2')
def item_view(request):
    jquery.need()
    try:
        id=int(request.matchdict['id'])
    except:
        return 'Invalid ID'
    #get item by id
    item=request.dbsession.query(Item).filter(Item.id==id).first()
    if not Item:
        return HTTPNotFound()

    # 导航栏的分类列表
    categories = request.dbsession.query(Category).filter_by(parent_id=None).all()

    #当前商品的分类信息
    category_old=request.dbsession.query(Category).filter_by(id=item.category.parent_id).first()

    # 当前的年月,拼接后续的默认时间
    now_year_month = time.strftime('%Y-%m', time.localtime(time.time()))
    #当月热销榜
    item_bills = request.dbsession.query(Item).filter(Item.category_id == item.category.id,func.strftime('%Y-%m',Item.add_time)==now_year_month).order_by('num desc').limit(3).all()
    #评论信息
    comments=request.dbsession.query(Comment).filter_by(item_id=item.id).all()

    return {'item':item,'title':u'商品详细','category':item.category,'categories':categories,'category_old':category_old,'item_bills':item_bills,'comments':comments}


@view_config(route_name='order',renderer='../templates/order.jinja2',permission='user')
def order_view(request):
    user_id = request.user.id
    orders=request.dbsession.query(Order).filter_by(user_id=user_id).all()
    # 导航栏的分类列表
    categories = request.dbsession.query(Category).filter_by(parent_id=None).all()

    return {'title':u'我的订单','orders':orders,'categories':categories}

class LoginSchema(colander.MappingSchema):
    choices = (('1', u'不保留'), ('2', u'1天'),
               ('3', u'1周'), ('4', u'1月'))
    username=colander.SchemaNode(colander.Str(),title=u'用户名',required=True)
    password=colander.SchemaNode(colander.Str(),title=u'密码',widget=deform.widget.PasswordWidget(),required=True)

    pepper = colander.SchemaNode(
        colander.String(),
        validator=colander.OneOf([x[0] for x in choices]),
        widget=deform.widget.RadioChoiceWidget(values=choices, inline=True),
        title=u'保留')


@view_config(route_name='login',renderer='../templates/login.jinja2')
def login_view(request):
    schema=LoginSchema()
    form=deform.Form(schema=schema,buttons=("登录",))
    username=request.params.get('username',None)
    password=request.params.get('password',None)
    if not username:
        return {
            'title':u'登录',
            'message':'',
            'form':form.render()
        }
    else:
        try:
            appstruct=form.validate(request.POST.items())
        except deform.ValidationFailure, e:
            return {
                'title': u'登录',
                'form': e.render()
            }
        user=request.dbsession.query(User).filter_by(name=username).first()
        if not user:
            return {
                 'title':u'登录',
                'message':u'用户名不存在'
            }
        elif user.password!=password:
            return {
                'title': u'登录',
                'message': u'密码错误'
            }
    #save user.id
    request.session['userid']=user.id
    headers=remember(request,user.id)
    return HTTPFound(location=request.route_url('home'),headers=headers)

class RegsisterSchema(colander.MappingSchema):
    username=colander.SchemaNode(
        colander.Str(),
        title=u'用户名',
        description=u'(*必填，至少两位)',
        validator=colander.Length(min=2, max=20),
    )
    password=colander.SchemaNode(
        colander.Str(),
        title=u'密码',
        widget=deform.widget.PasswordWidget(),
        validator=colander.Length(min=6,max=20),
        description = u'(*必填，至少六位)'
    )
    repassword = colander.SchemaNode(
        colander.Str(),
        title=u'重复密码',
        validator=colander.Length(min=6, max=20),
        widget=deform.widget.PasswordWidget(),
        description=u'(*必填，同上)'
    )

def password_validate(form,value):
    password=value['password']
    repassword=value['repassword']

    if password!=repassword:
        raise colander.Invalid(form,u'密码和重复密码不相等')

@view_config(route_name='register',renderer='../templates/register.jinja2')
def register_view(request):
    username=request.params.get('username',None)
    password=request.params.get('password',None)
    repassword=request.params.get('repassword',None)
    schema=RegsisterSchema(validator=password_validate)
    form=deform.Form(schema=schema,buttons=('注册',))

    if not username:
        return {
            'title':u'注册',
            'message':'',
            'form':form.render()
        }
    else:
        try:
            appstruct=form.validate(request.POST.items())
        except deform.ValidationFailure,e:
            return {
                'title': u'注册',
                'form': e.render()
            }
        user=request.dbsession.query(User).filter_by(name=appstruct['username']).first()
        if user:
            return {
                 'title':u'注册',
                'message':u'用户名已存在'
            }
        else:
            user_obj=User()
            user_obj.name=appstruct['username']
            user_obj.password=appstruct['password']
            request.dbsession.add(user_obj)
            return HTTPFound(location=request.route_url('login'))

@view_config(route_name='shoping_cart',renderer='../templates/shoping_cart.jinja2',permission='user')
def shoping_cart_view(request):
    user_id=request.session['userid']
    carts=request.dbsession.query(Cart).filter_by(user_id=user_id).all()
    # 导航栏的分类列表
    categories = request.dbsession.query(Category).filter_by(parent_id=None).all()
    return {'title':u'我的购物车','carts':carts,'categories':categories}

#登出
@view_config(route_name='logout')
def logout_view(request):
    del request.session['user']
    headers=forget(request)
    return HTTPFound(location=request.route_url('hone'),headers=headers)

class AddItemSchema(colander.MappingSchema):
    name = colander.SchemaNode(
        colander.Str(),
        title=u'商品名称'
    )
    price = colander.SchemaNode(
        colander.Decimal(),
        title=u'价格',
        widget=deform.widget.MoneyInputWidget(options={'allowZero':True,'min':0})
    )
    description = colander.SchemaNode(
        colander.Str(),
        title=u'介绍',
        widget=deform.widget.TextAreaWidget(rows=10,cols=5)
    )

@view_config(route_name='add_item',renderer='../templates/add_item.jinja2',permission='item')
def add_item_view(request):
    name=request.params.get('name',None)
    price = request.params.get('price', None)
    description=request.params.get('description',None)
    schema = AddItemSchema()
    form = deform.Form(schema, buttons=('sumbit',))
    categories = request.dbsession.query(Category).filter_by(parent_id=None).all()
    category = request.dbsession.query(Category).filter_by(id=request.matchdict.get('id', None)).first()
    if 'name' in request.params:
        try:
            appstruct=form.validate(request.POST.items())
        except deform.ValidationFailure,e:
            return {'title':u'增加商品','categories':categories,'category':category,'form':e.render()}
        item=Item()
        item.name=appstruct['name']
        item.price=appstruct['price']
        item.description=appstruct['description']
        item.category=request.dbsession.query(Category).filter_by(id=request.matchdict.get('id', None)).first()
        request.dbsession.add(item)
        return HTTPFound(location=request.route_url('category',id=request.matchdict.get('id', None)))
    else:
        return {'title':u'增加商品','categories':categories,'category':category,'form':form.render()}

@view_config(route_name='buy',renderer='jsonp')
def buy_view(request):
    if request.session.get('userid',None):
        user_id=request.session['userid']
        item_id=request.POST.get('item_id',None)
        item_num=request.POST.get('item_num',1)

        if item_id:
            cart=Cart()
            cart.user=request.dbsession.query(User).filter_by(id=user_id).first()
            cart.items=request.dbsession.query(Item).filter_by(id=item_id).all()
            cart.item_num=item_num
            request.dbsession.add(cart)
            return {'status':1}
        else:
            return {'status':-1}
    else:
        return {'status':0}



db_err_msg = """\
Pyramid is having a problem using your SQL database.  The problem
might be caused by one of the following things:

1.  You may need to run the "initialize_MyProject_db" script
    to initialize your database tables.  Check your virtual
    environment's "bin" directory for this script and try to run it.

2.  Your database server may not be running.  Check that the
    database server referred to by the "sqlalchemy.url" setting in
    your "development.ini" file is running.

After you fix the problem, please restart the Pyramid application to
try it again.
"""
